#/bin/env python3
# -*- encoding=utf8 -*-
#******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# Author: wangchong
# Create: 2021-09-11
# ******************************************************************************
"""
modify pckg-mgmt.yaml
"""

import os
import sys
import yaml
import shutil
import argparse
import datetime

par = argparse.ArgumentParser()
par.add_argument("-pm", "--pckg_mgmt", default=None,
        help="pckg_mgmt.yaml file path", required=True)
par.add_argument("-bf", "--branch_from", default=None,
        help="branch from", required=True)
par.add_argument("-bt", "--branch_to", default=None, 
        help="branch to", required=True)
par.add_argument("-of", "--obs_from", default=None, 
        help="obs from", required=True)
par.add_argument("-ot", "--obs_to", default=None, 
        help="obs to", required=True)
par.add_argument("-pkgs", "--pkglist", default=None, 
        nargs="+", help="add packages list", required=True)
args = par.parse_args()

datestr = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")

if not os.path.exists(args.pckg_mgmt):
    print("The pckg_mgmt.yaml file is not exist!")
    sys.exit(1)

def read_yaml(file_path):
    if os.path.exists(file_path):
        with open(file_path, "r", encoding='utf-8') as f:
            file_msg = yaml.load(f, Loader=yaml.FullLoader)
    return file_msg

def write_yaml(dict_msg, file_path):
    with open(file_path, "w", encoding='utf-8') as f:
        yaml.dump(dict_msg, f, default_flow_style=False, sort_keys=False)

def modify_file_msg(pckg_msg):
    add_msg = []
    for pkg in args.pkglist:
        tmp = {'name': pkg, 'branch_from': args.branch_from, 'branch_to': args.branch_to, 
                'obs_from': args.obs_from, 'obs_to': args.obs_to, 'date': datestr}
        add_msg.append(tmp)
    pckg_msg['packages']['natural'].extend(add_msg)
    return pckg_msg

def modify_pckg_yaml():
    pckg_msg = read_yaml(args.pckg_mgmt)
    new_pckg_msg = modify_file_msg(pckg_msg)
    new_pckg_mgmt_yaml = os.path.join(os.getcwd(), "new_pckg_mgmt.yaml")
    write_yaml(new_pckg_msg, new_pckg_mgmt_yaml)
    print("The modified pckg-mgmt.yaml is in ", new_pckg_mgmt_yaml)

modify_pckg_yaml()
